import requests
import time
import threading
from queue import Queue

# 配置参数
delay = 3  # 每 3 秒获取一次新 IP，根据代理池api修改
api_url = 'http://58ip.top/api/get?token=3cb83e7fe2fb0553eb5169ffd34526&number=1000&type=http&format=1'#代理池api，淘宝上可以买
check_url = 'https://httpbin.org/ip'  # 用于验证 IP 的网址
thread_count = 50#线程数量
output_file = '/root/proxy.txt'

# 全局变量
available_ips = []
ip_queue = Queue()
lock = threading.Lock()

# 从 代理池API 获取 IP 列表
def get_ips_from_api():
    while True:
        try:
            response = requests.get(api_url, timeout=10)
            if response.status_code == 200:
                new_ips = response.text.strip().split('\n')
                for ip in new_ips:
                    ip_queue.put(ip.strip())
        except Exception as e:
            print(f'获取 IP 列表时出错: {e}')
        time.sleep(delay)

# 验证 IP 是否可用
def check_ip(ip):
    proxies = {
        'http': f'http://{ip}',
        'https': f'http://{ip}'
    }
    try:
        response = requests.get(check_url, proxies=proxies, timeout=5)
        if response.status_code == 200:
            return True
    except:
        pass
    return False

# 工作线程函数
def worker():
    global available_ips
    while True:
        ip = ip_queue.get()
        if check_ip(ip):
            with lock:
                available_ips.append(ip)
                available_ips = available_ips[-50:]   #实时更新可用IP数量上限
                save_ips_to_file()
        ip_queue.task_done()

# 将可用 IP 保存到文件
def save_ips_to_file():
    global available_ips
    try:
        with open(output_file, 'w') as f:
            f.write('\n'.join(available_ips))
    except Exception as e:
        print(f'保存 IP 到文件时出错: {e}')

if __name__ == '__main__':
    # 启动获取 IP 的线程
    api_thread = threading.Thread(target=get_ips_from_api, daemon=True)
    api_thread.start()

    # 启动工作线程
    for _ in range(thread_count):
        t = threading.Thread(target=worker, daemon=True)
        t.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('程序终止')